<?php
require_once(dirname(__FILE__) . '/app.php');
check_login();
//http://shuiguo.liofis.com/pin.php?id=ZTMTA0&act=pin&pin_id=1
$id = abs(intval($_GET['id']));

//pin
$act = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'dan';

$pin_id = isset($_REQUEST['pin_id']) ? intval($_REQUEST['pin_id']) : '0';
if($pin_id >0){
	$tmp_pin_order = Table::Fetch('pin_order', $pin_id);

	if($tmp_pin_order['state'] == 1)
	{
		Session::Set('error', '该拼团已成团，您将重新开团。');
		$pin_id = 0;//重新开团
	}
	else if($tmp_pin_order['state'] == 2 || $tmp_pin_order['endtime'] <= time())
	{
		Session::Set('error', '该拼团已过期，您将重新开团。');
		$pin_id = 0;//重新开团
	} else {
		//检测是否已经参团
		$pin_order_list = DB::LimitQuery('pin_order_list',array(
			'condition' => array('pin_id'=>$pin_id)
		));
		foreach($pin_order_list as $pin_order_val)
		{
			$tmp_order = Table::Fetch('order', $pin_order_val['order_id']);
			//user_id
			if($login_user_id == $tmp_order['user_id'] && $tmp_order['state'] == 'pay')
			{
				Session::Set('error', '您已参加该拼团，继续购买将重新开团。');
				$pin_id = 0;//重新开团
				break;
			}
		}
	}
}



$team = Table::Fetch('team', $id);

if ( !$team || $team['begin_time']>time() ) {
	Session::Set('error', '团购项目不存在');
	redirect( WEB_ROOT . '/index.php' );
}

/* 查询快递清单 */
if ($team['delivery'] == 'express') {
	$express_ralate = unserialize($team['express_relate']);
	foreach ($express_ralate as $k=>$v) {
		$express[$k] = Table::Fetch('category',$v['id']);
		$express[$k]['relate_data'] = $v['price'];
	}
}

/* 查询用户收货地址*/
	$c = array('user_id'=>$login_user_id);
	$address = DB::LimitQuery('address',array(
		'condition' => $c,
		'order' => 'ORDER BY id DESC',
	));
	$def = DB::LimitQuery('address',array(
		'condition' => array('user_id'=>$login_user_id,'default'=>'Y'),
	));

	$default_addr = array();
	if(!empty($def)) {
		$default_addr = $def[0];
	}

$ex_con = array(
		'user_id' => $login_user_id,
		'team_id' => $team['id'],
		'state' => 'unpay',
		'rstate' => 'normal',
		);
$order = DB::LimitQuery('order', array(
	'condition' => $ex_con,
	'one' => true,
));


//peruser buy count 删除数量限制
if ($team['max_number']>0) $team['per_number'] = $team['max_number'] - $team['now_number'];

$has_address = false;

	if(!empty($default_addr)) {
		$has_address = true;
		//$express_id =$default_addr['id'];
	}
	$express_node = array_pop($express);
	$express_id =  $express_node['id']; 
	
	
	$express_price = $express_node['relate_data'];
	$condbuy = '';
	isset($_POST['quantity']) ? '' : $_POST['quantity']=1;
	$table = new Table('order', $_POST);
	
	$table->quantity = abs(intval($table->quantity));
	
	if ($order && $order['state']=='unpay') {
		$table->SetPk('id', $order['id']);
	}

	$table->user_id = $login_user_id;
	$table->state = 'unpay';
	$table->allowrefund = $team['allowrefund'];
	$table->team_id = $team['id'];
	$table->city_id = $team['city_id'];
	$table->express = ($team['delivery']=='express') ? 'Y' : 'N';
	$table->fare = $table->express=='Y' ? $express_price : 0;
	$table->express_id = $table->express=='Y' ? $express_id : 0;
	$table->price = $act == 'pin' ? $team['pin_price'] : $team['team_price'];
	$table->credit = 0;
	$table->condbuy = $condbuy;
	
	/*用户收货地址*/
	if ($team['delivery'] == 'express' && !empty($default_addr)) {
			$table->realname = $default_addr['name'];
			$table->zipcode = $default_addr['zipcode'];
			$table->mobile = $default_addr['mobile'];
			$table->address = $default_addr['province'].  $default_addr['city']. $default_addr['area'].$default_addr['street'];
	}
	if ( $table->id ) {
		$eorder = Table::Fetch('order', $table->id);
		
		if ($eorder['state']=='unpay' 
				&& $eorder['team_id'] == $id
				&& $eorder['user_id'] == $login_user_id
		   ) {
			 $is_pin =   $eorder['is_pin'] == 1 ? true : false;
			$table->origin = team_origin($team, $table->quantity,$express_price,$is_pin );
			$table->origin -= $eorder['card'];
		} else {
			$eorder = null;
		}
	}
	if (!$eorder){
		$table->pk_value='';
		$table->create_time = time();
		 $is_pin =   $act == 'pin' ? true : false;
		$table->origin = team_origin($team, $table->quantity,$express_price,$is_pin );
		$table->is_pin =   $act == 'pin' ? 1 : 0;
	}
	//pin_id
	$insert = array(
			'user_id', 'team_id', 'city_id', 'state','is_pin', 'express_id',
			'fare', 'express_xx','express', 'origin', 'price',
			'address', 'zipcode', 'realname', 'mobile', 
			'quantity', 'create_time', 'remark', 'condbuy',
		);
	if($team['allowrefund']=='Y') $insert[] = 'allowrefund' ;
	if ($flag = $table->update($insert)) {
		$order_id = abs(intval($table->id));
		
		if($act == 'pin')
		{
			//var_dump($eorder);die();
			//拼团开始
			if(!$eorder){
				//新订单，旧订单无需处理
				if($pin_id>0)
				{
					//邀请的拼团，无需插入pin_order表，只要新增该拼团记录
					//id,pin_id,order_id,createtime 
					$p_order_list = array();
					$p_order_list['pin_id'] = $pin_id;
					$p_order_list['order_id'] = $order_id;
					$p_order_list['createtime'] = time();
					DB::Insert('pin_order_list', $p_order_list);
				} else {
					/**
					pin_order 新开的 拼团，需要插入pin_order 表
					id,state,need_count,finish_time,createtime
					**/
					$pin_order = array();
					$pin_order['state'] = 0;
					$pin_order['need_count'] = $team['min_number'];
					$pin_order['finish_time'] = 0;
					$pin_order['createtime'] = time();
					$pin_order['endtime'] = time()+86400*$team['pin_day'];
					
					
					$pin_id = DB::Insert('pin_order', $pin_order);
					
					$p_order_list = array();
					$p_order_list['pin_id'] = $pin_id;
					$p_order_list['order_id'] = $order_id;
					$p_order_list['createtime'] = time();
					DB::Insert('pin_order_list', $p_order_list);
				}
				
			}  else {
				
				if($pin_id>0)
				{
					//createtime 可能引起的bug是 团长移位。
					$SQL = "UPDATE pin_order_list set pin_id='{$pin_id}',createtime=".time()." WHERE order_id = '{$order_id}' ;";
					$rs = DB::Query($SQL);
				}
				
			}
			
		}
		
		
		/* 插入订单来源 */
		$data['order_id'] = $order_id;
		$data['user_id'] = $login_user_id;
		$data['referer'] = $_COOKIE['referer'];
		$data['create_time'] = time();
		DB::Insert('referer', $data);
		
		redirect(WEB_ROOT."/order/check.php?id={$order_id}");
	}



include template('team_buy');
